import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from models import Thing, User
import random, string, base64, urllib

class NewHandler(webapp.RequestHandler):
  def get(self):
    # Get the logged in user and make sure they are in the db
    # TODO: This code will be at the top of every page, move into a seperate class
    self.loggedInUser = users.get_current_user()
    
    userQuery = User.gql('WHERE uniqueid = :1 LIMIT 1', self.loggedInUser.user_id())
    # If the user is not in the datastore, add them
    if (userQuery.count() == 0):
      # Add user to db
      user = User()
      user.name = self.loggedInUser.nickname()
      user.uniqueid = self.loggedInUser.user_id()
      user.put()
    else:
      # If they are already in show the id (just for debug purposes)
      user = userQuery.get()
    
    # Get a list of a number of strings with given length
    length = 24
    number = 1
    strings = self.getStrings(length, number)
    
    ## Loop through and output the QR Code images from Google Charts API
    for x in range(0,number):
      self.response.out.write('<img src="http://chart.apis.google.com/chart?cht=qr&chs=250x250&chld=M&chl=http://matttesting.latest.mangtug.appspot.com/ndm/thing/' + strings[x] + '" alt="QR Code of a NDM Thing" />')
  
  # Get list of a number of random string of a given length
  def getStrings(self, length, number):
    # Create a list
    list = []
    
    # Loop the number of strings and append a random string to the list
    for x in xrange(number):
      list.append(self.getString(length))
    
    # Return the list to the caller
    return list
  
  # A method to get a random string of ASCII characters of a given length and make sure it doesn't already exist
  def getString(self, length):
    # Get a random string
    # TODO: Make this random string generator less horrible
    generatedString = "".join([random.choice(string.ascii_letters + string.digits + ".-") for i in xrange(length)])
    
    # Check the string doesn't exist
    thingQuery = Thing.gql('WHERE thingid = :1 LIMIT 1', generatedString)
    if (thingQuery.count() == 0):
      # Add the generated string to the db so we know not to generate it again
      thing = Thing()
      thing.thingid = generatedString
      thing.author = self.loggedInUser.user_id()
      thing.put()
      
      # Return the string
      return generatedString
    else:
      # Use recursion to get a different one
      return self.getString(length)

class UnusedHandler(webapp.RequestHandler):
  def get(self):
    # Get the logged in user and make sure they are in the db
    # TODO: This code will be at the top of every page, move into a seperate class
    loggedInUser = users.get_current_user()
    
    userQuery = User.gql('WHERE uniqueid = :1 LIMIT 1', loggedInUser.user_id())
    # If the user is not in the datastore, add them
    if (userQuery.count() == 0):
      # Add user to db
      user = User()
      user.name = loggedInUser.nickname()
      user.uniqueid = loggedInUser.user_id()
      user.put()
    else:
      # If they are already in show the id (just for debug purposes)
      user = userQuery.get()
    
    thingQuery = Thing.gql('WHERE author = :1 AND assigned = False', user.uniqueid)
    if (thingQuery.count() > 0):
      self.response.out.write('<h1>' + str(thingQuery.count()) + ' unused codes</h1>')
      
      for result in thingQuery:
        self.response.out.write('<p>Code: ' + result.thingid + '<br />')
        self.response.out.write('<img src="http://chart.apis.google.com/chart?cht=qr&chs=250x250&chld=M&chl=http://matttesting.latest.mangtug.appspot.com/ndm/thing/' + result.thingid + '" alt="QR Code of a NDM Thing" /></p>')
    else:
      self.response.out.write('No unused codes')

class MainHandler(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()

    if user:
      user_nick = user.nickname()
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
      template_values = {
	'user_nick': user_nick,
	'url': url,
	'url_linktext': url_linktext,
	}
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'login'
      template_values = {
	'url': url,
	'url_linktext': url_linktext,
	}

    path = os.path.join(os.path.dirname(__file__), 'templates', 'ndm_main.html')
    self.response.out.write(template.render(path, template_values))

def main():
  application = webapp.WSGIApplication([
    ('/ndm/generate/new/*', NewHandler),
    ('/ndm/generate/unused/*', UnusedHandler),
    ('/ndm/*', MainHandler),
  ], debug=True)
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()
